<template>
  <div class="app-container">
    <el-form ref="queryForm" :inline="true">
      <el-form-item :label="$t('area.Layer')" prop="postName">
        <treeselect
          v-model="mapId"
          size="small"
          :placeholder="$t('operating.pleaseChosen')"
          :show-count="true"
          :max-height="600"
          :options="mapTreeData"
          :default-expand-level="1"
          @input="nodeClick"
        />
      </el-form-item>
      <!-- <el-form-item
        :label="$t('history.date')"
        prop="postName"
      >
        <el-date-picker
          v-model="timeValue1"
          type="datetime"
          :placeholder="$t('operating.StartTime')"
          size="small"
          @change="change1"
        />
        -
        <el-date-picker
          v-model="timeValue2"
          type="datetime"
          :placeholder="$t('operating.EndTime')"
          size="small"
          @change="change2"
        />

      </el-form-item> -->
      <el-form-item :label="$t('history.deptname')" prop="postName">
        <treeselect
          v-model="deptValue"
          size="small"
          :placeholder="$t('operating.pleaseChosen')"
          :show-count="true"
          :max-height="600"
          :options="depts"
          :default-expand-level="1"
          @input="getFilterObjData"
        />
      </el-form-item>
      <el-form-item :label="$t('history.objValue')" prop="postName">
        <el-select
          v-model="model"
          size="small"
          :clearable="true"
          :placeholder="$t('operating.pleaseChosen')"
          filterable
        >
          <el-option
            v-for="item in modelCount"
            :key="item.idx"
            :label="item.name"
            :value="item.resourceId"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="query"
          >{{ $t("operating.search") }}</el-button
        >
         <el-button
            type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="down"
          >导出</el-button
        >
      </el-form-item>
    </el-form>

    <div class="context">
      <div id="map" />
    </div>

    <!-- 左下角坐标显示和缩放比例 -->
    <div class="positiondiv">
      <span />
    </div>
    <div class="scalediv">
      <span />
    </div>
  </div>
</template>

<script>
import i18n from "@/utils/lang/index";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {
  sendThis,
  Load_Map,
  _iMap,
  _TransPixel,
  TagStyle,
  _Style,
  updateOverlayPosition,
  FenceStyle,
  _TransMetric,
  _TransMetricFence,
  _dPR,
} from "@/utils/historyMap.js";
import {
  webSockUrl,
  webSockStatisticsUrl,
  cameraServerUrl,
  baseUrl,
  initPicPath,
  webSockMonitorUrl,
  rateHeartShow,
} from "@/utils/global";
import { GeoJSON } from "ol/format.js";
import { Vector as VectorSource } from "ol/source.js";
import { Vector as VectorLayer } from "ol/layer.js";
import Feature from "ol/Feature";
import Point from "ol/geom/Point";
import { LineString } from "ol/geom.js";
import { Style, Stroke } from "ol/style.js";
import { listDept } from "@/api/system/dept";
import { getMapTree, getMap } from "@/api/location";

import {
  getDeptTree,
  getDeptDetail,
  getAllDeptDetail,
  getHistoryInfoDetail,
  exportSingleOrMoreDate,
  history
} from "@/api/system/historyDisplayInfo.js";

import { treeselect } from "@/api/system/dept";

export default {
  components: { Treeselect },
  data() {
    return {
      mapId: "",
      oldMapId: null,
      mapTreeData: [],
      radio: "1",
      timeValue1: new Date(new Date().getTime() - 1000 * 60 * 30),
      timeValue2: new Date(),
      model: "",
      modelCount: [],
      TagSource: null,
      TagLayer: null,
      lineSource: null,
      lineLayer: null,
      temp: 100,
      trackData: [],
      currentPos: 1,
      feature_: null,
      setTImeOut_: null,
      tempCount: [
        {
          value: 50,
          label: "16x",
        },
        {
          value: 100,
          label: "8x",
        },
        {
          value: 200,
          label: "4x",
        },
        {
          value: 400,
          label: "2x",
        },
      ],
      posLength: 0,
      rloading: [],
      depts: [],
      deptValue: null,
      progressIndex: 0,
    };
  },
  mounted() {
    this.initData();
    this.getDeptList();

    // // 刚打开时，部门默认不选择，此时，人员应该显示所有
    getAllDeptDetail().then((res) => {
      const RES = this.responseUse(res);
      this.modelCount = RES;
    });
  },
  beforeDestroy() {
    clearTimeout(this.setTImeOut_);
  },
  methods: {
    initData() {
      // 加载地图树
      getMapTree().then((res) => {
        const RES = this.responseUse(res);
        if (typeof RES !== "undefined") {
          this.mapTreeData = RES;
          sendThis(this);
          this.mapId = RES[0].id;
        }
      });
    },
    nodeClick() {
      if (this.oldMapId == this.mapId) {
        this.$message({
          message: i18n.t("realtime.areaQequired"),
          type: "warning",
        });
      } else if (this.mapId !== undefined) {
        this.oldMapId = this.mapId;
        getMap(this.mapId).then((res) => {
          const RES = this.responseUse(res);
          if (RES != undefined) {
            $("#map").empty();
            Load_Map(
              baseUrl + "/file" + RES.mapPath,
              RES.mapActualX,
              RES.mapActualY,
              RES.mapPixelX,
              RES.mapPixelY,
              RES.mapPixelX / RES.mapActualX,
              [RES.mapOriginX, RES.mapOriginY],
              false
            );
            this.loadLayer();
          }
        });
      }
    },
    // 切换部门时，更新对象数据
    getFilterObjData(val) {
      // 把部门对象选择框清空掉
      if (val != undefined) {
        // 选择有部门
        getDeptDetail(val).then((res) => {
          const RES = this.responseUse(res);
          this.modelCount = RES;
          this.model = "";
        });
      } else {
        getAllDeptDetail().then((res) => {
          const RES = this.responseUse(res);
          this.modelCount = RES;
          this.model = "";
        });
      }
    },
    //  获取部门列表
    getDeptList() {
      // getDeptTree().then((res) => {
      //   const RES = this.responseUse(res)
      //   if (typeof RES !== 'undefined') {
      //     this.depts = RES
      //   }
      // });
      treeselect().then((res) => {
        const RES = this.responseUse(res);
        if (typeof RES !== "undefined") {
          this.depts = this.handleTree(RES, "deptId");
        }
      });
      // getDeptTree().then((res) => {
      //   const RES = this.responseUse(res)
      //   if (typeof RES !== 'undefined') {
      //     this.depts = RES
      //   }
      // })
    },
    change1() {
      if (this.timeValue1 > this.timeValue2) {
        var tt = this.timeValue1.getTime();
        var ntt = tt + 1000 * 60 * 120;
        this.timeValue2 = new Date(ntt);
      }
    },
    change2() {
      if (this.timeValue2 < this.timeValue1) {
        var tt = this.timeValue2.getTime();
        var ntt = tt - 1000 * 60 * 120;
        this.timeValue1 = new Date(ntt);
      }
    },
    //导出
    down(){
         const that = this;
      if (this.mapId == "" || this.model == "") {
        this.$message({
          message: i18n.t("Notice.selectLayerOrQueryObject"),
        });
        return;
      }
       var param = {
        mapId: this.mapId,
        resourceId: this.model,
        deptId: this.deptValue,
       
      }
        this.download('/system/history/exportSingleOrMoreDate', {
        ...param
      }, `data${new Date().getTime()}.xls`)
      
    },
    query() {

      const that = this;
      if (this.mapId == "" || this.model == "") {
        this.$message({
          message: i18n.t("Notice.selectLayerOrQueryObject"),
        });
        return;
      }
       var param = {
        'mapId': this.mapId,
        'resourceId': this.model,
        'deptId': this.deptValue,
       
      }
history(param).then((res) => {
      let data = res.data;
      let a = {
        features: [
          {
            type: "Feature",
            geometry: { coordinates: [1430.37, 1532.08], type: "Point" },
          },
        ],
        type: "FeatureCollection",
      };

      data.forEach((element) => {
        a.features[0].geometry.coordinates = [element.posX,element.posY];
        var format = new GeoJSON();
        let newFeatures = format.readFeatures(a);

        newFeatures.forEach(function (f) {
          let coord = f.getGeometry().getCoordinates();
          f.getGeometry().setCoordinates(_TransPixel(coord));
          f.set("type", element.type);
          f.set("name", element.resourceName);
          f.set("visible", true);
          f.set("workTypeName",element.workTypeName);
          console.log(_TransPixel(coord));
          that.TagSource.addFeature(f);
        });

      })
      });
    },
    // 加载地位图层和线图层,
    loadLayer() {
      this.TagSource = new VectorSource({
        wrapX: false,
      });
      this.TagLayer = new VectorLayer({
        source: this.TagSource,
        style: function (feature) {
          return TagStyle(feature, 0);
        },
      });
      this.lineSource = new VectorSource({
        wrapX: false,
      });
      this.lineLayer = new VectorLayer({
        source: this.lineSource,
        style: new Style({
          stroke: new Stroke({
            color: "green",
            width: 3,
          }),
        }),
      });
      _iMap.addLayer(this.lineLayer);
      _iMap.addLayer(this.TagLayer);
    },
    // 定时画线，定时更新点位位置
    drawLine() {
      var self = this;
      self.progressIndex = self.currentPos;
      if (self.currentPos > self.posLength || self.posLength == 0) {
        return;
      }
      if (
        self.currentPos == self.posLength ||
        self.currentPos == self.posLength - 1
      ) {
        // 点位移动
        var from = _TransPixel([
          self.trackData[self.posLength - 1].posX,
          self.trackData[self.posLength - 1].posY,
        ]);

        self.feature_.getGeometry().setCoordinates(from);
      } else {
        var from = _TransPixel([
          self.trackData[self.currentPos].posX,
          self.trackData[self.currentPos].posY,
        ]);
        var to = _TransPixel([
          self.trackData[self.currentPos + 1].posX,
          self.trackData[self.currentPos + 1].posY,
        ]);
        // 点位移动
        self.feature_.getGeometry().setCoordinates(to);
        // 画线
        var lineFeature = new Feature(new LineString([from, to]));
        self.lineSource.addFeature(lineFeature);
      }
      self.currentPos++;
      self.setTImeOut_ = setTimeout(function () {
        self.drawLine();
      }, self.temp);
    },
    progressValueChange(val) {
      this.currentPos = val;
      this.lineSource.clear(true);
      if (this.posLength != 0) {
        $(".playbtn i").attr("class", "al-icon-carpause");
      }
      this.drawLine();
    },
    progressUIValue() {
      $(".playbtn i").attr("class", "al-icon-carplay");
      clearTimeout(this.setTImeOut_);
    },
    clickPlayBtn() {
      const className = $(".playbtn i").attr("class");
      if (className === "al-icon-carplay") {
        // 处于暂定状态
        $(".playbtn i").attr("class", "al-icon-carpause");
        this.drawLine();
      } else if (className === "al-icon-carpause") {
        // 处于播放状态
        $(".playbtn i").attr("class", "al-icon-carplay");
        clearTimeout(this.setTImeOut_);
      }
    },
    formatTooltip(val) {
      if (this.posLength != 0) {
        if (
          this.currentPos == this.posLength ||
          this.currentPos > this.posLength
        ) {
          return this.trackData[this.posLength - 1].speed;
        } else {
          return this.trackData[this.currentPos].speed;
        }
      }
    },
  },
};
</script>

<style scoped>
.handle-box {
  min-width: 1125px;
}

.handle-box * {
  float: left;
}

.handle-box span {
  line-height: 28px;
  margin-left: 30px;
}

.context {
  padding: 0;
  width: 100%;
  height: calc(100% - 60px);
  position: relative;
}
.context div {
  float: left;
}
#map {
  width: 100%;
  height: 100%;
}

.bottom_progress {
  position: absolute;
  width: 100%;
  height: 60px;
  bottom: 20px;
  display: grid;
  /* place-items: center;
   */
  place-content: end center;
}

>>> .vue-treeselect__control {
  width: 180px;
}

/deep/ .el-button--mini.is-circle {
  width: 36px;
  height: 36px;
}
</style>
